<template>
  <div class="container">
    <a-card class="general-card" :title="title" ref="tableRef">
      <a-row v-if="!isEmpty(formType)">
        <a-col :flex="1">
          <pro-form
            table
            :gutter="50"
            ref="formRef"
            :form-json="formType"
            :form-data="formData"
            @search="setRefresh"
            v-model:loading="loadingBtn"
            @resetForm="setRefresh({})"
          >
          </pro-form>
        </a-col>
      </a-row>
      <a-divider v-if="!isEmpty(formType)" style="margin-top: 10px" />
      <!--   操作栏   -->
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <slot name="btns"></slot>
            <a-button v-if="showExpande" type="dashed" @click="toggleExpanded">
              <template #icon>
                <icon-expand v-if="expandedKeys.length === 0" />
                <icon-shrink v-else />
              </template>
              <template #default>
                {{ expandedKeys.length !== 0 ? '折叠' : '展开' }}
              </template>
            </a-button>
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-tooltip content="刷新">
            <div class="action-icon" @click="setRefresh()">
              <icon-refresh size="18" />
            </div>
          </a-tooltip>
          <a-tooltip content="全屏">
            <div class="action-icon" @click="toggleFullScreen()">
              <icon-fullscreen-exit size="18" />
            </div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip content="密度">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip content="列设置">
            <a-popover
              trigger="click"
              position="lb"
              :visible="popoverVisible"
              hide-trigger="none"
              @popup-visible-change="popupVisibleChange"
            >
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div
                    v-for="(item, index) in currentColumns"
                    :key="item.dataIndex"
                    class="setting"
                  >
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox
                        v-model="item.checked"
                        @click.stop
                        @change="
                          handleChange($event, item as TableColumnData, index)
                        "
                      ></a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <!-- 修改：将 columns 属性绑定到 showColumns -->
      <a-table
        :row-key="rowKey"
        v-model:selectedKeys="selectedKeys"
        :row-selection="
          showRows
            ? {
                type: 'checkbox',
                showCheckedAll: true,
                onlyCurrent: false,
              }
            : undefined
        "
        :loading="loading"
        :columns="showColumns"
        :data="innerData"
        :size="size"
        :pagination="innerPagination"
        @page-size-change="onPageSizeChanage"
        @page-change="onPageChange"
        :default-page-size="20"
        v-bind="propField"
        v-model:expandedKeys="expandedKeys"
        @select="selectItem"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>
        <template #operations="{ column, record }">
          <a-space v-if="getMenus(column, record)?.length < 3">
            <template
              v-for="(item, index) in getMenus(column, record)"
              :key="index"
            >
              <a-link
                v-if="item.name !== '删除'"
                type="text"
                hoverable
                size="small"
                @click="item.onClick(record)"
                >{{ item.name }}</a-link
              >
              <a-popconfirm
                v-else
                style="display: inline"
                @ok="item.onClick(record)"
                position="left"
                type="error"
                content="删除后将不可恢复，真的要删除吗?"
              >
                <a-link hoverable type="text" size="small">{{
                  item.name
                }}</a-link>
              </a-popconfirm>
            </template>
          </a-space>
          <a-space v-else>
            <!-- 显示第一个操作项 -->
            <a-link
              type="text"
              hoverable
              size="small"
              @click="getMenus(column, record)[0].onClick(record)"
              >{{ getMenus(column, record)[0].name }}</a-link
            >

            <!-- 更多操作下拉菜单 -->
            <a-dropdown trigger="click" position="bl">
              <a-link type="text" size="small" hoverable style="width: 30px"
                ><svg
                  viewBox="0 0 48 48"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  stroke="currentColor"
                  class="arco-icon arco-icon-more"
                  stroke-width="4"
                  stroke-linecap="butt"
                  stroke-linejoin="miter"
                  style="color: rgb(22, 119, 255)"
                >
                  <path
                    d="M38 25v-2h2v2h-2ZM23 25v-2h2v2h-2ZM8 25v-2h2v2H8Z"
                    fill="currentColor"
                    stroke="none"
                  ></path>
                  <path
                    d="M38 25v-2h2v2h-2ZM23 25v-2h2v2h-2ZM8 25v-2h2v2H8Z"
                  ></path></svg
              ></a-link>
              <template #content>
                <a-doption
                  v-for="(item, index) in getMenus(column, record).slice(1)"
                  :key="index + 1"
                  @click="
                    () => {
                      if (item.name !== '删除') {
                        item.onClick(record);
                      } else if (item.name === '删除') {
                        // // handleDeleteClick();
                        // console.log('删除了', item);
                        item.onClick(record);
                      }
                    }
                  "
                >
                  <!--                  <template v-if="item.name === '删除'">-->
                  <!--                    <a-popconfirm-->
                  <!--                      @ok="item.onClick(record)"-->
                  <!--                      type="error"-->
                  <!--                      content="确认删除吗？"-->
                  <!--                      @click.stop-->
                  <!--                    >-->
                  <!--                      <span class="danger-text">{{ item.name }}</span>-->
                  <!--                    </a-popconfirm>-->
                  <!--                  </template>-->
                  <span>{{ item.name }}</span>
                </a-doption>
              </template>
            </a-dropdown>
          </a-space>
        </template>
        <template #id="{ record }"> </template>
        <template #status="{ column, record }">
          <a-badge
            v-for="option in filteredOptions(column, record)"
            :key="option.value"
            :status="option?.status"
            :text="option.label"
          />
        </template>

        <template #unitext="{ column, record }">
          {{ record[column.dataIndex] + '·' + record[column.selectOptions[0]] }}
        </template>

        <template #tags="{ column, record }">
          <a-tag
            v-for="option in filteredOptions(column, record)"
            :key="option.value"
            :color="option?.color"
          >
            {{ option.label }}
          </a-tag>
        </template>
        <template #icon="{ column, record }">
          <component :is="record[column.dataIndex]"></component>
        </template>
        <template #render="{ column, record }">
          column.dataIndex.render(record)
        </template>
        <template #sex="{ column, record }">
          <icon-man
            style="color: #165dff"
            v-if="record[column.dataIndex] === 2"
          />
          <icon-woman
            style="color: #f75260"
            v-if="record[column.dataIndex] === 3"
          />
        </template>
        <template #iconTitle="{ column, record }">
          <div style="display: flex; align-items: center">
            <a-link @click="column.onClick(record)">
              <svg-icon
                :name="record[column.iconName]"
                style="height: 2em; width: 2em; margin-right: 10px"
              ></svg-icon>
              {{ record[column.dataIndex] }}</a-link
            >
          </div>
        </template>
        <template #splitName="{ column, record }">
          <div style="display: flex; align-items: center">
            {{ record[column.firstName] }} 至 {{ record[column.lastName] }}
          </div>
        </template>
      </a-table>
      <slot name="options" />
    </a-card>
  </div>
</template>

<script setup lang="ts">
  import { Icon } from '@arco-design/web-vue';
  import { isEmpty } from 'lodash';
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import useLoading from '@/hooks/useLoading';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import cloneDeep from 'lodash/cloneDeep';
  import Sortable from 'sortablejs';
  import { isFunction } from 'lodash-es';
  import { useFullscreen } from '@vueuse/core';
  import { collectAllKeys } from '@/utils/utils';
  const popoverVisible = ref(false);
  const { loading, setLoading } = useLoading(false);
  const innerData = ref<any>();
  const selectedKeys = ref([]);
  const currentColumns = ref<Column[]>([]); // 完整列配置（含 checked 状态）
  const showColumns = computed(() =>
    currentColumns.value.filter((col) => col.checked)
  );

  defineOptions({
    name: 'settingRole',
  });

  const loadingBtn = ref(false);
  const formParams = ref({});

  const filteredOptions = computed(() => {
    return (column, record) => {
      if (record[column.dataIndex] === undefined) {
        return [];
      }
      const currentValue = Number(record[column.dataIndex]);
      return (column.options || []).filter(
        (option) => Number(option.value) === currentValue
      );
    };
  });
  const allExpandedKeys = ref([]);
  const expandedKeys = ref([]);

  const props = withDefaults(
    defineProps<{
      title?: string;
      formType?: object;
      request?: any;
      pagination?: object;
      tableType?: any;
      rowKey?: string;
      showRows?: boolean;
      propField?: object;
      showExpande?: boolean;
    }>(),
    {
      title: '',
      formType: () => ({}),
      tableType: () => [],
      pagination: () => ({}),
      showRows: false,
      showExpande: false,
    }
  );

  // 动态生成formData
  const initialFormData = ref({
    // 保留可能存在的初始字段
    org_state: null,
    // 动态生成字段
    ...props.formType.reduce((acc, item) => {
      acc[item.name] = null;
      return acc;
    }, {} as Record<string, any>),
  });

  // 最终使用的formData（保持响应式）
  const formData = ref({ ...initialFormData.value });

  const currentPage = ref(1);
  const pageSize = ref<number>(20);
  const totalSize = ref(0);

  const innerPagination = computed(() => {
    if (innerRequest) {
      return {
        current: Number(currentPage.value),
        pageSize: Number(pageSize.value),
        showPageSize: true,
        showTotal: true,
        ...props.pagination,
        total: totalSize.value,
      };
    }
    return props.pagination;
  });
  const selectItems = ref([]);
  const selectItem = (
    selectedRowKeys: any[],
    selectedRows: any[],
    records: any
  ) => {
    // 直接根据最新的selectedKeys和表格数据重新计算selectItems
    selectItems.value =
      innerData.value?.filter((item: any) =>
        selectedRowKeys.includes(item[props.rowKey])
      ) || [];
  };
  watch(
    () => selectedKeys.value,
    (newKeys) => {
      selectItems.value =
        innerData.value?.filter((item: any) =>
          newKeys.includes(item[props.rowKey])
        ) || [];
    },
    { deep: true }
  );
  const innerRequest = isFunction(props.request)
    ? async () => {
        setLoading(true);
        try {
          // 列表上传参数
          const params = {
            ...formParams.value,
            ...props?.formData,
          };
          const hasPagination = props.pagination !== false;
          if (hasPagination) {
            params.page_no = currentPage.value;
            params.page_size = pageSize.value;
          }
          const { data } = await props.request(params);

          if (props.showExpande) {
            allExpandedKeys.value = collectAllKeys(data.list);
          }
          if (first.value) first.value = false;
          if (hasPagination) {
            totalSize.value = data.total;
            // pageSize.value = data.page_size;
          }
          innerData.value = data.list;
        } finally {
          setLoading(false);
        }
      }
    : undefined;

  const first = ref(true);
  const refresh = () => {
    if (first.value) {
      currentPage.value = 1;
    }
    innerRequest();
  };

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };

  const generateFormModel = () => {
    return {
      number: '',
      name: '',
      contentType: '',
      filterType: '',
      createdTime: [],
      status: '',
    };
  };
  const formModel = ref(generateFormModel());
  const cloneColumns = ref([]);
  // const showColumns = ref<Column[]>([]);

  const size = ref<SizeProps>('medium');

  const densityList = computed(() => [
    {
      name: '迷你',
      value: 'mini',
    },
    {
      name: '偏小',
      value: 'small',
    },
    {
      name: '中等',
      value: 'medium',
    },
    {
      name: '偏大',
      value: 'large',
    },
  ]);

  watch(
    () => props.tableType,
    (val) => {
      const filteredColumns = val.filter(
        (item: Column) => item.dataIndex !== 'org_id'
      );
      currentColumns.value = filteredColumns.map((col) => ({
        ...col,
        checked: col.checked ?? true, // 默认选中
      }));
    },
    { deep: true, immediate: true }
  );

  onMounted(() => {
    refresh();
  });

  setLoading(false);
  const onPageChange = (current: number) => {
    currentPage.value = current;
    refresh();
  };
  // 设置表格密度
  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    _e: Event
  ) => {
    size.value = val as SizeProps;
  };
  // 列显示/隐藏切换
  const handleChange = (checked: boolean, column: Column, index: number) => {
    // 更新当前列的 checked 状态
    currentColumns.value = currentColumns.value.map((col, i) =>
      i === index ? { ...col, checked } : col
    );
  };

  // 列排序
  const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
  ): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      // 交换列位置
      newArray.splice(
        beforeIdx,
        1,
        newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
      );
    }
    return newArray;
  };

  const popupVisibleChange = (val: boolean) => {
    popoverVisible.value = val;
    if (val) {
      nextTick(() => {
        const el = document.getElementById('tableSetting') as HTMLElement;
        const sortable = new Sortable(el, {
          onEnd(e: any) {
            const { oldIndex, newIndex } = e;
            // 直接操作 currentColumns 的顺序
            exchangeArray(currentColumns.value, oldIndex, newIndex);
          },
        });
      });
    }
  };

  const visible = ref(false);
  const modelType = '';

  const rules = ref({
    name: [
      {
        message: '请输入',
        required: true,
      },
    ],
  });

  const onPageSizeChanage = (e: any) => {
    pageSize.value = e;
    refresh();
  };

  const tableRef = ref('tableRef');
  const { toggle: toggleFullScreen } = useFullscreen(tableRef);

  function setRefresh(e: any) {
    if (e) {
      formParams.value = e;
    }
    first.value = true;
    refresh();
  }
  defineExpose({
    setRefresh,
    selectedKeys,
    selectItems,
  });

  function toggleExpanded() {
    expandedKeys.value = expandedKeys?.value.length
      ? []
      : allExpandedKeys.value;
  }
  // 菜单操作相关处理
  type MenuItem = {
    name: string;
    onClick: (record: any) => void;
    disabled?: boolean; // 禁用状态
    hidden?: boolean; // 隐藏菜单（新增，用于过滤）
  };
  const getMenus = (column: any, record: any) => {
    if (!column.menus) return [];
    return isFunction(column.menus)
      ? (column.menus(record) as MenuItem[]).filter((menu) => !menu.hidden) // 类型断言
      : (column.menus as MenuItem[]).filter((menu) => !menu.hidden); // 过滤隐藏项
  };
</script>

<style scoped lang="less">
  .container {
    height: 100%;
  }

  .container {
    padding: 0 20px 20px;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }

  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }

  .setting {
    display: flex;
    align-items: center;
    width: 200px;

    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
